package com.lut.reservation.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lut.reservation.bean.Result;
import com.lut.reservation.bean.RoomReservation;
import com.lut.reservation.exception.BusinessException;
import com.lut.reservation.service.RoomReservationService;
import com.lut.reservation.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author zyt
 */
@Slf4j
@RestController
@RequestMapping("/api/room/reservation")
public class RoomReservationController extends BaseController<RoomReservationService, RoomReservation> {

  @Autowired
  private HttpSession session;

  @Override
  public QueryWrapper<RoomReservation> queryWrapper(Map<String, String> map) {
    Object userId = session.getAttribute("userId");
    if (userId == null) {
      throw new BusinessException("请先登录！");
    }
    final QueryWrapper<RoomReservation> queryWrapper = super.queryWrapper(map);
    if (map.containsKey("state")) {
      if ("reservation".equals(map.get("state"))) {
        queryWrapper.lambda().in(RoomReservation::getState, "INIT", "PASS", "CANCEL", "REJECT");
        queryWrapper.lambda().eq(RoomReservation::getUserId, session.getAttribute("userId"));
      }
      if ("finish".equals(map.get("state"))) {
        queryWrapper.lambda().in(RoomReservation::getState, "FINISH", "APPROVE", "REFUSE", "COMMENT");
        queryWrapper.lambda().eq(RoomReservation::getUserId, session.getAttribute("userId"));
      }
    }
    return queryWrapper;
  }

  @PostMapping("/finish/{id}")
  public Result<Void> finish(@PathVariable Integer id) {
    service.updateState(id, "COMMENT");
    return ResultUtil.success();
  }

  @PostMapping("/cancel/{id}")
  public Result<Void> cancel(@PathVariable Integer id) {
    service.updateState(id, "CANCEL");
    return ResultUtil.success();
  }

  @PostMapping("/reject/{id}")
  public Result<Void> reject(@PathVariable Integer id) {
    service.updateState(id, "REJECT");
    return ResultUtil.success();
  }

  @PostMapping("/approve/{id}")
  public Result<Void> approve(@PathVariable Integer id) {
    service.updateState(id, "APPROVE");
    return ResultUtil.success();
  }

  @PostMapping("/refuse/{id}")
  public Result<Void> refuse(@PathVariable Integer id) {
    service.updateState(id, "REFUSE");
    return ResultUtil.success();
  }

  @PostMapping("/pass/{id}")
  public Result<Void> pass(@PathVariable Integer id) {
    service.updateState(id, "PASS");
    return ResultUtil.success();
  }
}
